package controller.uu;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.PhotoDaoLocal;
import model.dao.RatingDaoLocal;
import model.dao.UserDaoLocal;
import model.entity.Album;
import model.entity.Photo;
import model.entity.Rating;
import model.entity.User;
import controller.CUtil;

/**
 * Servlet implementation class SViewPhoto
 */
public class SViewPhoto extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private RatingDaoLocal ratingDao;
	
	@EJB
	private UserDaoLocal userDao;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SViewPhoto() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String imageId=(String)request.getParameter("photoId");
		Photo photo=photoDao.findById(Integer.parseInt(imageId));
		Album album=null;
		for(Album a:photo.getAlbums()){
			if(!a.getFavorite()){
				album=a;
				break;
			}
		}
		request.setAttribute("currentUser", album.getUser());
		request.setAttribute("photo", photo);
		request.setAttribute("album", album);
		if(request.getSession().getAttribute("user")!=null){
			User user=(User)request.getSession().getAttribute("user");
			List<Rating> ratings=ratingDao.isUserRate(user.getId(), photo.getId());
			if(ratings!=null && ratings.size()!=0){
				request.setAttribute("userRatingExists", 1);
			}else{
				request.setAttribute("userRatingExists", 0);
			}
		}
		
		User user=(User)request.getSession().getAttribute("user");
		if(user!=null){
			user=userDao.findById(user.getId());
			Album favorites=user.getFavorite();
			boolean contains=false;
			for(Photo p:favorites.getPhotos()){
				if(p.equals(photo)){
					contains=true;
					break;
				}
			}
			if(contains){
				request.setAttribute("favorites", favorites);
			}
		}
		
		CUtil.redirecter(request, response, "uu/VViewPhoto.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
